package com.imooc.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @Description NIO客户端
 * @Author
 * @Date 2019/8/27 21:59
 **/
public class NioClient {
    /**
     * 启动
     */
    public  void start(String nickName) throws IOException {
        System.out.println("客户端启动成功！");
        /**
         * 连接服务器
         */
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));


        /**
         * 接受服务器端发送数据
         * 新开一个线程处理
         */
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);

        new Thread(new NioClientHandler(selector)).start();

        /**
         * 向服务器端发送数据
         */
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String request = scanner.nextLine();
            if(request!=null &&request.length()>0){
                socketChannel.write(Charset.forName("UTF-8").encode(nickName+" : "+request));
            }
        }

    }

    public static void main(String[] args) throws IOException {
        NioClient nioClient = new NioClient();
//        nioClient.start();
    }
}
